<template>
    <div :class="(className || 'svg') + '-wrap'" ref="svgWrap">
        <slot v-if="slotPos == 'front'"></slot>
        <svg :class="svgClass" ref="svgRef" @click="handleSvgClick">
            <use :xlink:href="iconName"></use>
        </svg>
        <slot v-if="slotPos == 'back'"></slot>
    </div>
</template>
<script lang="ts" setup>
import { computed, getCurrentInstance, onMounted, ref, watch } from "vue"
interface ISvgIcon {
    iconName: string
    className?: string
    iconSize?: number
    slotPos?: string
    color?: string
    style?: any
}
const props = withDefaults(defineProps<ISvgIcon>(), {
    className: "",
    iconSize: 1,
    slotPos: "back",
})
const { emit } = getCurrentInstance();
const iconName = computed(() => `#icon-${props.iconName}`)
const svgClass = computed(() => (props.className ? `svg-icon ${props.className}` : "svg-icon"))
const svgRef = ref<SVGElement>()
const svgWrap = ref<HTMLElement>()
const handleSvgClick = () => emit('handleSvgClick');
onMounted(() => {
    svgRef.value.style.width = props.iconSize + "em"
    svgRef.value.style.height = props.iconSize + "em"
    svgRef.value.style.lineHeight = props.iconSize + "em"
    svgRef.value.style.fill = props.color || ''

    if (props.style && JSON.stringify(props.style) !== "{}") {
        Object.keys(props.style).forEach(key => svgWrap.value.style[key] = props.style[key])
    }
})
watch(() => props.style, (newVal) => {
    if (newVal && JSON.stringify(newVal) !== "{}") {
        Object.keys(newVal).forEach(key => svgWrap.value.style[key] = newVal[key])
    }
})
</script>
<style scoped>
.svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    overflow: hidden;
}

use {
    fill: inherit;
}
</style>
